package com.lgit.Model4.hw05;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest3 {

    public static void main(String[] args) {
        Socket s = null;
        PrintStream ps = null;
        Scanner sc = null;
        BufferedReader br = null;
        try {
            s = new Socket("Lenovo-PC", 1220);
            ps = new PrintStream(s.getOutputStream());
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            sc = new Scanner(System.in);
            System.out.println("请输入昵称以进行聊天: ");
            String userName = sc.next();
            ps.println(userName);
            System.out.println("欢迎" + userName + "来到拉勾聊天室...");
            Thread t1 = new Thread(new ClientThread(s));
            t1.start();
            while (true) {
                String str1 = sc.next();
                ps.println(str1);
                if ("发送文件".equals(str1)) {
                    System.out.println("请输入要发送的文件名: ");
                    String fileName = sc.next();
                    File file = new File("src/com/lgit/Model4/hw05/TestFile/" + fileName);
                    if (file.exists()) {
                        //"src/com/lgit/Model4/hw05test/" + userName + "/" + fileName
                        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/com/lgit/Model4/hw05/" + userName + fileName));
                        byte[] brr = new byte[1024];
                        int res = 0;
                        while((res = bis.read(brr)) != -1){
                            bos.write(brr,0,res);
                            //bos.flush();
                        }
                        bis.close();
                        bos.close();
                        System.out.println(fileName + "发送成功");
                        ps.println(fileName);
                    } else {
                        System.out.println(fileName + "文件不存在");
                    }
                } else if ("bye".equalsIgnoreCase(str1)) {
                    System.out.println("聊天结束，成功退出聊天室");
                    t1.stop();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != sc) {
                sc.close();
            }
        }
    }
}
